<template>
  <div class="img2img-template">
    <div class="header">
      <h2>图生图模板</h2>
      <div class="actions desktop-only">
        <el-button @click="router.back()">返回</el-button>
        <el-button type="primary" @click="generateImage" :loading="generating">
          生成图片
        </el-button>
      </div>
      <!-- 移动端顶部操作栏 -->
      <div class="mobile-header-actions mobile-only">
        <el-button icon-only circle @click="router.back()">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧参数配置 -->
      <div class="params-section" :class="{ 'mobile-hidden': showMobilePreview && generatedImages.length > 0 }">
        <el-form 
          ref="formRef"
          :model="formData"
          label-width="120px"
          class="template-form"
          :label-width="mobileLabelWidth"
        >
          <el-card class="form-card">
            <template #header>
              <div class="card-header">
                <span>基础参数</span>
                <!-- <div class="preset-controls">
                  <el-select v-model="currentPreset" placeholder="选择预设" size="small" @change="loadPreset">
                    <el-option v-for="preset in presets" :key="preset.name" :label="preset.name" :value="preset.name" />
                  </el-select>
                  <el-button size="small" @click="saveCurrentPreset" :disabled="!formData.prompt">保存预设</el-button>
                </div> -->
              </div>
            </template>

            <!-- 图片上传区域 -->
            <el-form-item label="上传图片" prop="init_image">
              <el-upload
                class="image-uploader"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                action="/api/v1/upload"
                :headers="uploadHeaders"
              >
                <img v-if="formData.init_image" :src="formData.init_image" class="uploaded-image" />
                <el-icon v-else class="upload-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">请上传一张图片作为生成基础</div>
            </el-form-item>

            <el-form-item label="提示词" prop="prompt">
              <el-input
                v-model="formData.prompt"
                type="textarea"
                :rows="3"
                placeholder="请输入图片描述"
              />
            </el-form-item>

            <el-form-item label="反向提示词" prop="negative_prompt">
              <el-input
                v-model="formData.negative_prompt"
                type="textarea"
                :rows="2"
                placeholder="请输入不需要的元素描述"
              />
            </el-form-item>

            <el-form-item label="图片尺寸" prop="size">
              <el-select v-model="formData.size">
                <el-option label="512 x 512" value="512x512" />
                <el-option label="768 x 768" value="768x768" />
                <el-option label="1024 x 1024" value="1024x1024" />
              </el-select>
            </el-form-item>

            <el-form-item label="生成数量" prop="batch_size">
              <el-input-number 
                v-model="formData.batch_size"
                :min="1"
                :max="4"
              />
            </el-form-item>
          </el-card>

          <el-card class="form-card">
            <!-- <template #header>
              <div class="card-header">
                <div class="header-with-switch">
                  <span>高级参数</span>
                  <el-switch v-model="showAdvanced" />
                </div>
              </div>
            </template> -->

            <template v-if="1">
              <!-- <el-form-item label="采样方法" prop="sampler">
                <el-select v-model="formData.sampler">
                  <el-option label="Euler a" value="Euler a" />
                  <el-option label="DPM++ 2M Karras" value="DPM++ 2M Karras" />
                  <el-option label="DPM++ SDE Karras" value="DPM++ SDE Karras" />
                  <el-option label="Euler" value="euler" />
                  <el-option label="DPM++ 2M" value="dpmpp_2m" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="采样步数" prop="steps">
                <el-slider
                  v-model="formData.steps"
                  :min="20"
                  :max="50"
                  :step="1"
                  show-input
                />
              </el-form-item>

              <el-form-item label="CFG Scale" prop="cfg_scale">
                <el-slider
                  v-model="formData.cfg_scale"
                  :min="1"
                  :max="20"
                  :step="0.5"
                  show-input
                />
              </el-form-item>

              <el-form-item label="变形强度" prop="denoising_strength">
                <el-slider
                  v-model="formData.denoising_strength"
                  :min="0"
                  :max="1"
                  :step="0.01"
                  show-input
                />
              </el-form-item>

              <el-form-item label="种子" prop="seed">
                <el-input-number 
                  v-model="formData.seed"
                  :min="-1"
                  :max="2147483647"
                  controls-position="right"
                />
                <el-button @click="formData.seed = -1" style="margin-left: 10px">
                  随机
                </el-button>
              </el-form-item>
            </template>
          </el-card>
        </el-form>
      </div>

      <!-- 右侧图片显示 -->
      <div class="preview-section" :class="{ 'mobile-fullscreen': showMobilePreview && generatedImages.length > 0 }">
        <!-- 进度显示 -->
        <div v-if="generating" class="progress-bar">
          <div class="progress-header">
            <span class="progress-title">生成进度</span>
            <span class="progress-percentage">{{ currentProgress }}%</span>
          </div>
          <el-progress 
            :percentage="currentProgress" 
            :stroke-width="15"
            :show-text="false"
            :status="currentProgress >= 100 ? 'success' : ''"
          />
          <div class="node-info" v-if="currentNodeInfo">
            <el-tag size="small" effect="plain">{{ currentNodeInfo.node }}</el-tag>
            <span>{{ currentNodeInfo.description || '' }}</span>
          </div>
          <div class="progress-detail">
            <el-icon v-if="currentProgress < 100"><Loading /></el-icon>
            <el-icon v-else><SuccessFilled /></el-icon>
            {{ progressDetail || '准备中...' }}
          </div>
        </div>

        <el-card v-if="generatedImages.length > 0" class="result-card">
          <template #header>
            <div class="card-header">
              <span>生成结果</span>
              <!-- 移动端返回表单按钮 -->
              <el-button 
                v-if="showMobilePreview" 
                size="small" 
                class="mobile-only"
                @click="showMobilePreview = false"
              >
                返回表单
              </el-button>
            </div>
          </template>
          <div class="image-grid">
            <div 
              v-for="(image, index) in generatedImages" 
              :key="index"
              class="image-item"
              @click="openImagePreview(image)"
            >
              <img :src="image.url" :alt="`生成图片 ${index + 1}`" />
              <div class="image-actions">
                <el-button size="small" circle @click.stop="downloadImage(image)">
                  <el-icon><Download /></el-icon>
                </el-button>
                <el-button size="small" circle @click.stop="useAsInput(image)">
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <div 
          v-else-if="!generating" 
          class="empty-preview"
        >
          <el-empty description="生成结果将显示在这里" />
        </div>
      </div>
    </div>

    <!-- 移动端底部操作栏 -->
    <div class="mobile-action-bar mobile-only">
      <el-button 
        v-if="generatedImages.length > 0 && !showMobilePreview"
        type="success" 
        class="view-results-btn"
        @click="showMobilePreview = true"
      >
        查看结果
      </el-button>
      <el-button 
        type="primary" 
        :loading="generating"
        class="generate-btn"
        @click="generateImage"
      >
        生成图片
      </el-button>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" width="80%" destroy-on-close>
      <img v-if="previewImage" :src="previewImage.url" style="width: 100%;" />
    </el-dialog>

    <!-- 保存预设对话框 -->
    <el-dialog v-model="savePresetDialogVisible" title="保存预设" width="30%">
      <!-- <el-form :model="presetForm">
        <el-form-item label="预设名称" required>
          <el-input v-model="presetForm.name" placeholder="请输入预设名称"></el-input>
        </el-form-item>
      </el-form> -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="savePresetDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSavePreset">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { request } from '@/utils/request';
import { wsService } from '@/services/websocket.service';
import type { GeneratedImage } from '@/types/comfyui';
import { Plus, Loading, SuccessFilled, Download, RefreshRight, ArrowLeft } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 表单数据
const formData = reactive({
  prompt: '',
  negative_prompt: '',
  size: '512x512',
  batch_size: 1,
  sampler: 'Euler a',
  steps: 30,
  cfg_scale: 7,
  seed: -1,
  denoising_strength: 0.75,
  init_image: ''
});

// 状态变量
const generating = ref(false);
const showAdvanced = ref(false);
const currentProgress = ref(0);
const progressDetail = ref('');
const currentNodeInfo = ref<{ node: string; description: string } | null>(null);
const generatedImages = ref<GeneratedImage[]>([]);
const previewVisible = ref(false);
const previewImage = ref<GeneratedImage | null>(null);
const savePresetDialogVisible = ref(false);
const presetForm = reactive({ name: '' });
const currentPreset = ref('');
const presets = ref<{ name: string; data: any }[]>([]);
const formRef = ref();
const uploadHeaders = ref({});

// 移动端相关状态
const showMobilePreview = ref(false);
const mobileLabelWidth = computed(() => {
  // 在小屏幕上减少标签宽度
  return window.innerWidth < 768 ? '90px' : '120px';
});

// 生命周期钩子
onMounted(() => {
  // 加载预设
  loadPresets();
  
  // 设置上传头信息
  uploadHeaders.value = {
    // 如果需要认证，可以在这里添加
  };
  
  // 设置WebSocket事件监听
  wsService.on('generation_progress', handleProgress);
  wsService.on('generation_complete', handleComplete);
  wsService.on('generation_error', handleError);
});

onUnmounted(() => {
  // 移除WebSocket事件监听
  wsService.off('generation_progress', handleProgress);
  wsService.off('generation_complete', handleComplete);
  wsService.off('generation_error', handleError);
});

// WebSocket 事件处理函数
const handleProgress = (data: any) => {
  console.log('Generation progress data:', data);
  
  try {
    // 解析后端传递的数据
    if (data && typeof data === 'object') {
      // 获取进度值和节点信息
      let progressValue = 0;
      let nodeInfo = null;
      
      // 处理直接传递的 comfyui_data 数据
      if (data.comfyui_data) {
        const comfyData = data.comfyui_data;
        
        // 处理不同类型的 ComfyUI 消息
        if (comfyData.value !== undefined && comfyData.max) {
          // 计算百分比进度
          progressValue = Math.round((comfyData.value / comfyData.max) * 100);
          nodeInfo = {
            node: comfyData.node || '处理中',
            description: getNodeDescription(comfyData.node)
          };
        }
      } 
      // 处理简化的进度信息
      else if (data.progress !== undefined) {
        progressValue = Math.max(0, Math.min(100, Number(data.progress)));
        nodeInfo = getStageFromProgress(progressValue);
      }
      
      // 更新 UI 状态
      currentProgress.value = progressValue;
      if (nodeInfo) {
        currentNodeInfo.value = nodeInfo;
        progressDetail.value = nodeInfo.description;
      }
    }
  } catch (error) {
    console.error('处理进度数据失败:', error);
    // 错误处理，但不中断用户体验
  }
};

// 获取节点对应的描述
const getNodeDescription = (nodeName: string): string => {
  if (!nodeName) return '处理中...';
  
  const nodeDescriptions: Record<string, string> = {
    'KSampler': '生成图像中...',
    'CLIPTextEncode': '编码提示词...',
    'EmptyLatentImage': '创建画布...',
    'VAEDecode': '解码图像...',
    'SaveImage': '保存图像...',
    'LoadImage': '加载输入图像...',
    'VAEEncode': '编码输入图像...'
  };
  
  return nodeDescriptions[nodeName] || `处理节点: ${nodeName}`;
};

// 根据进度百分比推测当前处理阶段
const getStageFromProgress = (progress: number): {node: string; description: string} => {
  if (progress < 5) {
    return { node: 'LoadImage', description: '加载输入图像...' };
  } else if (progress < 10) {
    return { node: 'VAEEncode', description: '编码输入图像...' };
  } else if (progress < 15) {
    return { node: 'CLIPTextEncode', description: '处理提示词中...' };
  } else if (progress < 85) {
    return { node: 'KSampler', description: `生成图像中... (${progress}%)` };
  } else if (progress < 95) {
    return { node: 'VAEDecode', description: '解码图像中...' };
  } else {
    return { node: 'SaveImage', description: '保存图像中...' };
  }
};

// 处理完成事件
const handleComplete = (data: any) => {
  console.log('Generation complete data:', JSON.stringify(data, null, 2));
  
  try {
    // 停止生成状态
    generating.value = false;
    currentProgress.value = 100;
    progressDetail.value = '生成完成';
    
    // 处理不同格式的完成数据
    if (data.comfyui_data) {
      // 处理ComfyUI直接返回的数据结构
      console.log('直接处理comfyui_data:', data.comfyui_data);
      
      // 数据可能是数组或对象
      const comfyData = Array.isArray(data.comfyui_data) 
        ? data.comfyui_data[0] 
        : data.comfyui_data;
      
      if (comfyData && comfyData.output) {
        // 直接从ComfyUI数据中提取图片
        const images = extractImagesFromOutput(comfyData.output);
        generatedImages.value = images;
        
        if (images.length > 0) {
          ElMessage.success('生成成功');
          return;
        }
      }
    }
    
    // 兼容之前格式: 检查outputs字段
    if (data.outputs) {
      handleGenerationComplete(data.outputs);
      return;
    }
    
    // 如果都没有找到图片数据
    console.warn('未在输出中找到图片数据:', data);
    ElMessage.warning('未找到生成的图片，请检查日志');
  } catch (err) {
    console.error('处理完成数据失败:', err);
    ElMessage.error('处理生成结果失败');
    generating.value = false;
  }
};

// 从输出中提取图片
const extractImagesFromOutput = (output: any): GeneratedImage[] => {
  const images: GeneratedImage[] = [];
  
  // 确保ComfyUI API URL有效
  const comfyuiUrl = import.meta.env.COMFYUI_API_URL || 'http://192.168.1.9:8188';
  
  // 检查输出是否有images字段
  if (output && output.images && Array.isArray(output.images)) {
    console.log('从output.images提取图片:', output.images);
    
    // 从images数组提取图片
    output.images.forEach((image: any) => {
      if (image.filename) {
        images.push({
          url: `${comfyuiUrl}/view?filename=${image.filename}${image.subfolder ? `&subfolder=${image.subfolder}` : ''}`,
          filename: image.filename
        });
      }
    });
  }
  
  // 如果没有找到图片，尝试递归搜索对象
  if (images.length === 0 && typeof output === 'object') {
    console.log('尝试递归搜索图片...');
    
    const findImages = (obj: any, path = '') => {
      if (!obj || typeof obj !== 'object') return;
      
      // 检查是否有filename字段
      if (obj.filename && typeof obj.filename === 'string') {
        // 使用ComfyUI的view接口获取图片
        const subfolder = obj.subfolder || '';
        images.push({
          url: `${comfyuiUrl}/view?filename=${obj.filename}${subfolder ? `&subfolder=${subfolder}` : ''}`,
          filename: obj.filename,
          path: path
        });
      }
      
      // 递归搜索所有字段
      for (const key in obj) {
        findImages(obj[key], `${path}.${key}`);
      }
    };
    
    findImages(output);
  }
  
  console.log('提取到的图片:', images);
  return images;
};

// 处理生成完成
const handleGenerationComplete = (outputs: any) => {
  try {
    console.log('处理生成输出:', outputs);

    if (!outputs || typeof outputs !== 'object') {
      throw new Error('无效的输出数据');
    }

    // 确保ComfyUI API URL有效
    const comfyuiUrl = import.meta.env.COMFYUI_API_URL || 'http://192.168.1.9:8188';
    console.log('使用ComfyUI URL:', comfyuiUrl);

    // 打印完整的输出结构以便调试
    console.log('输出数据结构:', JSON.stringify(outputs, null, 2));

    // 获取图片列表（适配ComfyUI输出格式）
    const images = Object.entries(outputs)
      .filter(([nodeId, output]) => {
        // 更详细的过滤逻辑，确保我们能获取到图片
        console.log(`节点 ${nodeId} 输出:`, output);
        return output && output.images && Array.isArray(output.images) && output.images.length > 0;
      })
      .flatMap(([nodeId, output]) => {
        console.log(`提取节点 ${nodeId} 的图片:`, output.images);
        return output.images.map(image => ({
          url: `${comfyuiUrl}/view?filename=${image.filename}${image.subfolder ? `&subfolder=${image.subfolder}` : ''}`,
          filename: image.filename,
          nodeId: nodeId  // 记录来源节点，方便调试
        }));
      });

    console.log('提取的图片:', images);

    if (images.length === 0) {
      // 使用递归搜索查找图片
      const alternativeImages = [];
      
      const findImages = (obj: any, path = '') => {
        if (!obj || typeof obj !== 'object') return;
        
        if (obj.filename && typeof obj.filename === 'string') {
          const subfolder = obj.subfolder || '';
          alternativeImages.push({
            url: `${comfyuiUrl}/view?filename=${obj.filename}${subfolder ? `&subfolder=${subfolder}` : ''}`,
            filename: obj.filename,
            path: path
          });
        }
        
        // 递归查找
        for (const key in obj) {
          findImages(obj[key], `${path}.${key}`);
        }
      };
      
      for (const key in outputs) {
        findImages(outputs[key], key);
      }
      
      if (alternativeImages.length > 0) {
        console.log('使用备选方法提取的图片:', alternativeImages);
        generatedImages.value = alternativeImages;
        ElMessage.success('生成成功');
        return;
      }
      
      throw new Error('未生成任何图片');
    }

    // 更新显示
    generatedImages.value = images;
    ElMessage.success('生成成功');
  } catch (error) {
    console.error('处理生成结果失败:', error);
    ElMessage.error(error instanceof Error ? error.message : '处理生成结果失败');
  }
};

// 处理错误事件
const handleError = (data: any) => {
  console.log('Generation error data:', JSON.stringify(data, null, 2));
  
  generating.value = false;
  currentProgress.value = 0;
  progressDetail.value = '';
  
  // 从不同可能的位置提取错误信息
  const errorMessage = 
    data.message || 
    data.error || 
    data.data?.error || 
    data.data?.message || 
    '生成失败';
    
  ElMessage.error(errorMessage);
};

// 生成图片
const generateImage = async () => {
  try {
    // // 检查用户是否已登录
    // const token = localStorage.getItem('token');
    // if (!token) {
    //   // 用户未登录，显示确认对话框
    //   ElMessageBox.confirm(
    //     '生成图片需要登录，是否前往登录页面？',
    //     '未登录提示',
    //     {
    //       confirmButtonText: '去登录',
    //       cancelButtonText: '取消',
    //       type: 'warning',
    //     }
    //   )
    //     .then(() => {
    //       // 保存当前页面路径，登录后可以重定向回来
    //       const currentPath = router.currentRoute.value.fullPath;
    //       router.push(`/login?redirect=${encodeURIComponent(currentPath)}`);
    //     })
    //     .catch(() => {
    //       // 用户取消登录，不执行任何操作
    //       ElMessage.info('您取消了登录');
    //     });
    //   return;
    // }

    if (!formData.init_image) {
      ElMessage.warning('请先上传一张图片');
      return;
    }

    if (!formData.prompt) {
      ElMessage.warning('请输入提示词');
      return;
    }

    // 设置生成状态
    generating.value = true;
    currentProgress.value = 0;
    progressDetail.value = '准备中...';
    
    // 解析尺寸
    const [width, height] = formData.size.split('x').map(Number);
    
    // 处理种子值 - 确保种子值为非负数
    let seedValue = formData.seed;
    if (seedValue < 0) {
      // 如果是-1（随机种子），生成一个随机的非负整数
      seedValue = Math.floor(Math.random() * 2147483647);
    }
    
    // 准备参数 - 确保参数名称与后端工作流节点期望的一致
    const params = {
      prompt: formData.prompt,
      negative_prompt: formData.negative_prompt || '',
      width: width,
      height: height,
      batch_size: formData.batch_size,
      // 修改采样器名称为ComfyUI支持的格式
      sampler_name: mapSamplerName(formData.sampler),
      steps: formData.steps,
      cfg_scale: formData.cfg_scale,
      seed: seedValue, // 使用处理后的种子值
      denoising_strength: formData.denoising_strength,
      init_image: formData.init_image
    };
    
    console.log('发送图生图请求:', params);
    
    // 发送请求 - 确保使用正确的工作流ID
    const response = await request('/api/v1/workflows/generate', {
      method: 'POST',
      body: {
        workflow_id: '67a9a31dbe1ceb79e75291e6', // 确认这是正确的图生图工作流ID
        params
      }
    });
    
    console.log('生成任务创建成功:', response);
    
    // 订阅WebSocket更新
    if (response.prompt_id) {
      wsService.subscribeToTask(response.prompt_id);
    } else {
      throw new Error('未获取到任务ID');
    }
  } catch (error) {
    generating.value = false;
    console.error('创建生成任务失败:', error);
    ElMessage.error('创建生成任务失败: ' + (error instanceof Error ? error.message : '未知错误'));
  }
};

// 添加采样器名称映射函数
const mapSamplerName = (sampler: string): string => {
  // 映射前端采样器名称到ComfyUI支持的名称
  const samplerMap: Record<string, string> = {
    'Euler a': 'euler_ancestral',
    'DPM++ 2M Karras': 'dpmpp_2m_karras',
    'DPM++ SDE Karras': 'dpmpp_sde_karras'
  };
  
  return samplerMap[sampler] || 'euler_ancestral'; // 默认使用 euler_ancestral
};

// 图片上传相关函数
const beforeUpload = (file: File) => {
  // 验证文件类型
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  
  // 验证文件大小
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!');
    return false;
  }
  
  return true;
};

// 处理图片上传成功
const handleUploadSuccess = (response: any, file: any) => {
  console.log('图片上传成功:', response);
  
  // 确保响应格式正确
  if (response.success && response.data && response.data.url) {
    // 使用完整的URL路径
    formData.init_image = response.data.url;
  } else if (response.url) {
    // 兼容不同的响应格式
    formData.init_image = response.url;
  } else {
    ElMessage.error('图片上传失败: 无效的响应格式');
    console.error('无效的上传响应:', response);
  }
};

// 使用生成的图片作为输入
const useAsInput = (image: GeneratedImage) => {
  formData.init_image = image.url;
  ElMessage.success('已设置为输入图片');
  
  // 滚动到表单顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 修改函数名，避免与变量冲突
const openImagePreview = (image: GeneratedImage) => {
  previewImage.value = image;
  previewVisible.value = true;
};

// 下载图片
const downloadImage = async (image: GeneratedImage) => {
  try {
    const response = await fetch(image.url);
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = image.filename || 'generated-image.png';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('下载图片失败:', error);
    ElMessage.error('下载图片失败');
  }
};

// 预设相关函数
const loadPresets = () => {
  try {
    const savedPresets = localStorage.getItem('img2img_presets');
    if (savedPresets) {
      presets.value = JSON.parse(savedPresets);
    }
  } catch (error) {
    console.error('加载预设失败:', error);
  }
};

const loadPreset = (presetName: string) => {
  const preset = presets.value.find(p => p.name === presetName);
  if (preset) {
    Object.assign(formData, preset.data);
    ElMessage.success(`已加载预设: ${presetName}`);
  }
};

const saveCurrentPreset = () => {
  presetForm.name = '';
  savePresetDialogVisible.value = true;
};

const confirmSavePreset = () => {
  if (!presetForm.name.trim()) {
    ElMessage.warning('请输入预设名称');
    return;
  }
  
  // 检查是否已存在同名预设
  const existingIndex = presets.value.findIndex(p => p.name === presetForm.name);
  
  if (existingIndex >= 0) {
    // 更新已有预设
    presets.value[existingIndex].data = { ...formData };
    ElMessage.success(`预设 "${presetForm.name}" 已更新`);
  } else {
    // 添加新预设
    presets.value.push({
      name: presetForm.name,
      data: { ...formData }
    });
    ElMessage.success(`预设 "${presetForm.name}" 已保存`);
  }
  
  // 保存到本地存储
  localStorage.setItem('img2img_presets', JSON.stringify(presets.value));
  
  // 更新当前预设
  currentPreset.value = presetForm.name;
  
  // 关闭对话框
  savePresetDialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
@use '@/assets/styles/responsive.scss' as responsive;

.img2img-template {
  padding: 20px;
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  position: relative;
  
  @include responsive.respond-to('sm') {
    padding: 16px;
    padding-bottom: 70px; // 为底部操作栏留出空间
  }
  
  @include responsive.respond-to('xs') {
    padding: 12px;
    padding-bottom: 70px;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h2 {
    margin: 0;
    font-size: 24px;
    
    @include responsive.respond-to('sm') {
      font-size: 20px;
    }
  }
}

.mobile-header-actions {
  display: flex;
  gap: 10px;
}

.main-content {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
  
  @include responsive.respond-to('lg') {
    gap: 16px;
  }
  
  @include responsive.respond-to('md') {
    flex-direction: column;
  }
}

.params-section {
  flex: 0 0 500px;
  overflow-y: auto;
  
  @include responsive.respond-to('lg') {
    flex: 0 0 450px;
  }
  
  @include responsive.respond-to('md') {
    flex: 0 0 auto;
  }
  
  &.mobile-hidden {
    @include responsive.respond-to('sm') {
      display: none;
    }
  }
}

.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
  
  &.mobile-fullscreen {
    @include responsive.respond-to('sm') {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 70px;
      z-index: 100;
      background-color: #fff;
      padding: 16px;
    }
  }
}

.form-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-with-switch {
  display: flex;
  align-items: center;
  gap: 12px;
}

.template-form {
  max-width: 100%;
  
  :deep(.el-form-item__label) {
    @include responsive.respond-to('xs') {
      padding-right: 6px;
    }
  }
  
  :deep(.el-upload) {
    width: 100%;
  }
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  
  @include responsive.respond-to('xs') {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
  }
}

.image-item {
  position: relative;
  cursor: pointer;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
  aspect-ratio: 1 / 1;
}

.image-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.empty-preview {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  min-height: 200px;
}

.actions {
  display: flex;
  gap: 12px;
}

/* 图片上传样式 */
.image-uploader {
  width: 100%;
  max-width: 300px;
  
  @include responsive.respond-to('xs') {
    max-width: 100%;
  }
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  
  @include responsive.respond-to('xs') {
    width: 100%;
    height: 150px;
  }
}

.uploaded-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
  border-radius: 6px;
  
  @include responsive.respond-to('xs') {
    width: 100%;
    height: 150px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

/* 进度条样式 */
.progress-bar {
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.progress-percentage {
  font-size: 16px;
  color: #409EFF;
  font-weight: 600;
  background: #ecf5ff;
  padding: 2px 8px;
  border-radius: 12px;
}

.progress-detail {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
  color: #606266;
  font-size: 14px;
}

.progress-detail .el-icon {
  font-size: 16px;
}

.progress-detail .el-icon.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.node-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
  font-size: 13px;
  color: #606266;
  background: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  
  @include responsive.respond-to('xs') {
    flex-direction: column;
    align-items: flex-start;
  }
}

.preset-controls {
  display: flex;
  gap: 8px;
  align-items: center;
  
  @include responsive.respond-to('xs') {
    flex-direction: column;
    align-items: flex-end;
    gap: 6px;
  }
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px;
  display: flex;
  justify-content: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.image-item:hover .image-actions {
  opacity: 1;
}

@include responsive.respond-to('sm') {
  .image-item .image-actions {
    opacity: 1;
  }
}

// 移动端底部操作栏
.mobile-action-bar {
  display: none;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 10px 16px;
  z-index: 101;
  
  @include responsive.respond-to('sm') {
    display: flex;
    gap: 10px;
  }
  
  .generate-btn {
    flex: 1;
    height: 44px;
    font-size: 16px;
  }
  
  .view-results-btn {
    flex: 1;
    height: 44px;
    font-size: 16px;
  }
}
</style>
